import os
from xml.dom.minidom import parse

import openpyxl

"""
根据默认的语言对比，找到需要翻译的key，并插入excel中首列
"""

default_string_file = 'res/origin/values/strings.xml'
origin_excel_dir = 'res/origin_excel/'
new_excel_dir = 'res/new_excel/'


def insert_key(source_file, target_file):
    dom = parse(default_string_file)
    string_nodes = dom.getElementsByTagName('string')

    # 默认语言的字符串值列表
    string_value_list = []
    string_key_list = []

    for node in string_nodes:
        for item in node.childNodes:
            string_value_list.append(item.nodeValue)
            string_key_list.append(node.getAttribute('name'))

    wb = openpyxl.load_workbook(source_file)
    sheet = wb[wb.sheetnames[0]]
    # 第一列插入key列
    sheet.insert_cols(1)
    sheet['A1'] = 'key'
    row = 0

    # 根据B列的值与字符串文件的值进行对比，获取到对应的key
    for cell in sheet['B']:
        row = row + 1
        value = cell.value.strip()
        value_without_terminator = value
        # 忽略末尾.的比对
        if '.' == value[len(value) - 1]:
            value_without_terminator = value[0:-1]
        if value in string_value_list or value_without_terminator in string_value_list:
            try:
                index = string_value_list.index(value)
            except Exception:
                index = string_value_list.index(value_without_terminator)
            sheet.cell(row, 1).value = string_key_list[index]

    wb.save(target_file)
    print('create target excel ' + target_file)


def main():
    files = os.listdir(origin_excel_dir)
    print("excel size is", len(files))
    for file in files:
        excel_path = origin_excel_dir + file
        new_excel_path = new_excel_dir + file[0:-5] + "_target.xlsx"
        insert_key(excel_path, new_excel_path)


if __name__ == '__main__':
    main()
